<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';

import { StashArrowReply } from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElMessage,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
} from 'element-plus';

import { getSalesChannelApi, getStoreStockDetailApi } from '#/api';
import CollapsibleCard from '#/components/collapsibleCard.vue';
import CurrentDateTime from '#/components/currentDateTime.vue';
import { getCommonShortcuts } from '#/utils';

const { locale } = useI18n();
const shortcuts = ref(getCommonShortcuts());

watch(locale, () => {
  shortcuts.value = getCommonShortcuts();
});

const submitForm: any = reactive({
  timeRange: [], // 统计日期
  channel: '', // 仓库
  pageNo: 1, // 页码
  pageSize: 50, // 每页条数
});

const lastCollectDate = ref<any>(null);

// 存储所有数据
const allData = ref<any>([]);
// 当前页数据
const tableData = ref<any>([]);
// 总数据量
const total = ref(0);

// 计算当前页数据
const currentPageData = computed(() => {
  const start = (submitForm.pageNo - 1) * submitForm.pageSize;
  const end = start + submitForm.pageSize;
  return allData.value.slice(start, end);
});

// 监听当前页数据变化
watch(currentPageData, (newData) => {
  tableData.value = newData;
});

const onSubmit = async () => {
  if (!submitForm.timeRange[0] || !submitForm.timeRange[1]) {
    ElMessage.warning('请选择统计日期！');
    return;
  }
  if (!submitForm.channel) {
    ElMessage.warning('请选择仓库！');
    return;
  }

  const params = {
    startDate: submitForm.timeRange[0],
    endDate: submitForm.timeRange[1],
    channelName: submitForm.channel,
  };

  const { data, systemLastDate } = await getStoreStockDetailApi(params);

  lastCollectDate.value = systemLastDate;

  // 处理数据格式化
  const nfArr = new Set(['barCode', 'bookName', 'publisher']);

  data.forEach((item: any) => {
    for (const key in item) {
      if (!nfArr.has(key) && !key.toLowerCase().includes('num')) {
        item[key] =
          String(item[key]) === 'infinity' || item[key] === 'NaN'
            ? '-'
            : item?.[key]?.toFixed(2) || '-';
      }
    }
  });

  // 存储所有数据
  allData.value = data;
  total.value = data.length;

  // 重置到第一页
  submitForm.pageNo = 1;
};

// 分页处理
const handleSizeChange = (val: number) => {
  submitForm.pageSize = val;
  submitForm.pageNo = 1; // 切换每页条数时重置到第一页
};

const handleCurrentChange = (val: number) => {
  submitForm.pageNo = val;
};

const router = useRouter();
const route = useRoute();

onMounted(() => {
  const kRaw = route.query.k;
  if (!kRaw) {
    router.push('/404');
    return;
  }
  dealUrlParams(kRaw);
  getChannelType();
  onSubmit();
});

const dealUrlParams = (params: any) => {
  const p = JSON.parse(params);
  submitForm.timeRange = p.timeRange;
  submitForm.channel = p.channel;
  if (p.pageNo) submitForm.pageNo = p.pageNo;
  if (p.pageSize) submitForm.pageSize = p.pageSize;
};

const getChannelType = async () => {
  const { data } = await getSalesChannelApi();
  options.channelOptions = data.map((item: any) => ({
    label: item,
    value: item,
  }));
};

const options = reactive<any>({
  channelOptions: [],
});

const sortBy = ref('');
const sortOrder = ref('');
const handleSortChange = ({ prop, order }: any) => {
  sortBy.value = prop;
  sortOrder.value = order;
  if (!order) {
    // 恢复原始顺序
    tableData.value = currentPageData.value;
    return;
  }
  const notNumber = new Set(['barCode', 'bookName']);
  // 对所有数据排序
  const sorted = [...allData.value].sort((a, b) => {
    const aVal = a[prop];
    const bVal = b[prop];
    if (notNumber.has(prop)) {
      return order === 'ascending'
        ? String(aVal).localeCompare(String(bVal))
        : String(bVal).localeCompare(String(aVal));
    } else {
      return order === 'ascending'
        ? Number(aVal) - Number(bVal)
        : Number(bVal) - Number(aVal);
    }
  });
  allData.value = sorted;
  // 重新分页
  tableData.value = currentPageData.value;
};
</script>

<template>
  <!-- 使用 mx-auto 实现左右外边距自动，justify-center 让子元素水平居中 -->
  <div
    class="relative mx-auto flex items-center justify-center space-x-8"
    style="height: calc(100vh - 88px)"
  >
    <CollapsibleCard>
      <ElForm
        :model="submitForm"
        label-position="top"
        @keyup.enter="onSubmit"
        disabled
      >
        <ElFormItem :label="$t('views.common.collectDate')">
          <ElDatePicker
            v-model="submitForm.timeRange"
            type="daterange"
            date-format="yyyy-MM-DD"
            value-format="YYYY-MM-DD"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('views.common.startDate')"
            :end-placeholder="$t('views.common.endDate')"
            :shortcuts="shortcuts"
          />
        </ElFormItem>
        <ElFormItem label="仓库">
          <ElSelect
            v-model="submitForm.channel"
            filterable
            clearable
            :placeholder="$t('views.common.pleaseSelect')"
          >
            <ElOption
              v-for="item in options.channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem>
          <div class="flex w-full justify-center">
            <ElButton type="primary" @click="onSubmit">
              {{ $t('views.common.filter') }}
            </ElButton>
          </div>
        </ElFormItem>
      </ElForm>
    </CollapsibleCard>
    <ElCard class="relative !ml-1 h-full flex-1 !overflow-auto">
      <div
        class="hover:text-primary absolute right-6 top-4 z-10 cursor-pointer rounded-full bg-white p-1 text-gray-500 shadow-md transition-shadow hover:bg-gray-100 hover:shadow-lg dark:bg-neutral-800 dark:text-gray-300"
        @click="router.back()"
      >
        <StashArrowReply class="size-5" />
      </div>
      <div
        class="hover:text-primary absolute left-6 top-4 z-10 cursor-pointer rounded-full bg-white p-1 text-gray-500 shadow-md transition-shadow hover:bg-gray-100 hover:shadow-lg dark:bg-neutral-800 dark:text-gray-300"
        @click="router.back()"
      >
        <StashArrowReply class="size-5" />
      </div>
      <h2 class="my-2 flex items-center justify-center text-base font-bold">
        {{
          `${$t('page.report.storeStockDetail')}(${$t('views.report.company')})`
        }}
      </h2>
      <h2 class="tems-center mb-2 flex justify-center text-base font-bold">
        {{ submitForm.channel }}
      </h2>
      <div class="flex justify-end text-xs">
        <div class="mr-4">最后数据时间：{{ lastCollectDate }}</div>
        <div class="mr-4">
          {{ $t('views.common.statisticalDate') }}：<span
            v-if="submitForm.timeRange[0] && submitForm.timeRange[1]"
          >
            {{ `${submitForm.timeRange[0]}` }} -
            {{ `${submitForm.timeRange[1]}` }}
          </span>
        </div>
        <CurrentDateTime />
      </div>
      <ElTable
        :data="tableData"
        border
        table-layout="auto"
        class="w-full"
        @sort-change="handleSortChange"
      >
        <ElTableColumn
          header-align="center"
          min-width="120"
          label="条形码"
          prop="barCode"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          min-width="150"
          label="图书名称"
          prop="bookName"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          width="80"
          label="定价"
          prop="price"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          min-width="120"
          label="出版社"
          prop="publisher"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          width="85"
          label="期初数量"
          prop="qcNum"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          label="期初码洋"
          prop="qcMayang"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          width="85"
          label="进货数量"
          prop="jhNum"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          label="进货码洋"
          prop="jhMayang"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          width="85"
          label="退货数量"
          prop="thNum"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          label="退货码洋"
          prop="thMayang"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          width="85"
          label="盘点数量"
          prop="pdNum"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          label="盘点码洋"
          prop="pdMayang"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          width="85"
          label="调拨数量"
          prop="dbNum"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          label="调拨码洋"
          prop="dbMayang"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          width="85"
          label="销售数量"
          prop="xsNum"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          label="销售码洋"
          prop="xsMayang"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          label="销售实洋"
          prop="xsShiyang"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          width="85"
          label="期末数量"
          prop="lastNum"
          sortable="custom"
        />
        <ElTableColumn
          header-align="center"
          align="right"
          label="期末码洋"
          prop="lastMayang"
          sortable="custom"
        />
      </ElTable>

      <!-- 分页组件 -->
      <div class="mt-4 flex justify-end">
        <ElPagination
          :current-page="submitForm.pageNo"
          :page-size="submitForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </ElCard>
  </div>
</template>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

:deep(.el-table .cell) {
  padding: 0 3px !important;
  white-space: nowrap;
}

:deep(.el-table__cell) {
  padding: 3px 0 !important;
  white-space: nowrap;
}
</style>
